from datetime import datetime
from database import db

class File(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.String(255), nullable=False)
    filepath = db.Column(db.String(255), nullable=False)
    filetype = db.Column(db.String(50), nullable=False)
    filesize = db.Column(db.Integer, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    issue_id = db.Column(db.Integer, db.ForeignKey('issue.id'), nullable=True)
    comment_id = db.Column(db.Integer, db.ForeignKey('comment.id'), nullable=True)
    uploaded_by = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    # 关系定义
    user = db.relationship('User')
    uploaded_by_user = db.relationship('User', foreign_keys=[uploaded_by])

    def is_image(self):
        return self.filetype.startswith('image/')

    def is_video(self):
        return self.filetype.startswith('video/')

    def is_audio(self):
        return self.filetype.startswith('audio/')

    def is_document(self):
        return not self.is_image() and not self.is_video() and not self.is_audio()

    def get_display_class(self):
        if self.is_image():
            return 'image'
        elif self.is_video():
            return 'video'
        elif self.is_audio():
            return 'audio'
        else:
            return 'document'
    
    def get_readable_size(self):
        """将文件大小转换为人类可读的格式"""
        size = self.filesize
        for unit in ['B', 'KB', 'MB', 'GB']:
            if size < 1024 or unit == 'GB':
                return f"{size:.2f} {unit}"
            size /= 1024

# 在models/__init__.py中导入这个模型
def init_file_model():
    pass